import { downloadFile } from "@/service/global";
import { message } from "antd";
import {
  isFloatOne,
  isFloatTwo,
  isInteger,
  isJustFloatOne,
  isJustFloatTwo,
  isJustInteger,
} from "./regExp";
import html2canvas from "html2canvas";

/**
 *
 * @param blobData 导出用到的blobData，直接使用request返回的数据
 * @param name 导出文件名
 * @param isChart 是否是图表那种直接走该方法，文件名不带后缀的的自定义导出excel
 */
export const exportExcel = (
  blobData: Blob,
  name: string,
  isChart?: boolean
) => {
  // console.log('blobData:', blobData);
  console.log("blobData:", blobData, typeof blobData);

  const reader = new FileReader();
  try {
    reader.readAsDataURL(blobData);
    reader.onload = () => {
      const link: any = document.createElement("a");
      link.href = reader.result;
      if (name.indexOf(".") > -1 && isChart) {
        link.download = name + ".xls";
      } else {
        link.download = name;
      }
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    };
  } catch (error) {
    console.log(error);

    message.error(error);
  }
};

/**
 *
 * @param blobData 导出用到的blobData，直接使用request返回的数据
 * @param name 导出文件名
 */
const viewFile = (blobData: Blob, name: string) => {
  console.log("blobData:", blobData);
  const reader = new FileReader();
  try {
    reader.readAsDataURL(blobData);
    reader.onload = () => {
      const link: any = document.createElement("a");
      link.href = reader.result;
      // console.log('reader.result', reader.result)
      const _imgUrl = reader.result;
      let PDFData = _imgUrl.replace(
        "data:application/octet-stream;base64,",
        ""
      );
      sessionStorage.setItem("_imgUrl", PDFData);
      // console.log('REACT_APP_ENV',REACT_APP_ENV)
      if (process.env.NODE_ENV == "production") {
        top.window.postMessage(
          { url: `/report-center/Pdf/web/viewer.html?id=${name}&name=${name}` },
          window.location.origin
        );
        // window.open(`/report-center/Pdf/web/viewer.html?id=${name}&name=${name}`);
      } else {
        window.open(`/Pdf/web/viewer.html?id=${name}&name=${name}`);
      }
    };
  } catch (error) {
    console.log(error);

    message.error(error);
  }
};

// 现在后端支持的是pdf，doc，png
export const DownLoad_File = async (
  bucketName: string,
  fileName: string,
  originalName?: string,
  type?: string
) => {
  console.log("xixxxxxxxxxxxxxxxxxx");

  const response: Blob = await downloadFile({ bucketName, fileName })
    .then((res) => {
      // console.log('res:', res)
      return res;
    })
    .catch((err) => {
      message.error("下载失败，请检查您的网络设置");
    });
  // console.log('response:', response)
  // const response: Blob = await downloadFile({ bucketName, fileName })
  // const fileType = ['pdf', 'doc', 'png']
  // 尽调记录那里 fileName 形如 ad89b64b1ab4466aabafa8524ae66ff3.doc.1609824030134
  // 需要转一下
  // console.log('download***********');
  console.log(
    bucketName,
    fileName,
    originalName,
    type,
    response,
    "-----------22----"
  );

  const file = fileName.split(".")[0];
  if (!response) {
    message.error("下载失败，请检查您的网络设置");
    return false;
  }
  if (type == "view") {
    viewFile(response, originalName || file);
  } else {
    exportExcel(response, originalName || file);
  }

  return false;
};

// 判断windows和mac
export const OSnow = () => {
  const agent = navigator.userAgent.toLowerCase();
  const isMac = /macintosh|mac os x/i.test(navigator.userAgent);
  if (agent.indexOf("win32") >= 0 || agent.indexOf("wow32") >= 0) {
    return "win32";
  }
  if (agent.indexOf("win64") >= 0 || agent.indexOf("wow64") >= 0) {
    return "win64";
  }
  if (isMac) {
    return "mac";
  }
};
/**
 *
 * @param name string url后跟的参数名
 */
export const getUrlParam = (name: string) => {
  const str: string = window.location.href.split("?")[1] || "";
  const regInset = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
  const r = str.match(regInset);
  //百分号decodeURI会报错，所以需要replace处理一下
  if (r) {
    const newstr = r[2].replace(/%/g, "baifenhao");
    return decodeURI(newstr).replace(/baifenhao/g, "%");
  }
  return "";
};

/**
 *
 * @param value 当前输入值
 * @param precision 保留小数位数
 * @param min 最小值，可控制正负
 * @param max 最大值
 * @returns 处理后的值
 * @author gf
 */
export const validateInput = (
  value,
  precision = 0,
  min?: number,
  max?: number
) => {
  const _IntegerNumber = () => {
    let str2;
    let reg;
    if (Math.abs(precision) > 0) {
      if (min >= 0) {
        reg = /[^\d\.]/g;
      } else {
        reg = /[^-?\d\.]/g;
      }
    } else {
      if (min >= 0) {
        reg = /[^\d]/g;
      } else {
        reg = /[^-?\d]/g;
      }
    }
    str2 = value.replace("。", ".").replace(reg, "");
    const arr_ = str2.split("-");
    let str: any;
    if (str2.indexOf("-") > -1) {
      if (arr_.length === 1) {
        str = arr_[0];
      } else if (arr_.length === 2) {
        str = !arr_[1] ? arr_[0] || "-" : "-" + _resolvePoint(arr_[1]);
      } else if (arr_.length === 3) {
        str = "-" + value.replaceAll("-", "");
      }
    } else {
      str = str2;
    }
    let valueTemp = str;
    if (str && str.length > 1 && str[0] === "0") {
      // message.error('请输入合法数字')
      valueTemp = parseFloat(str);
    }
    if (str.indexOf(".") > -1) {
      const arr = str.split(".");
      console.log(
        parseFloat(arr[0]),
        parseFloat(arr[0]) === parseFloat(arr[0])
      );
      if (arr[1]) {
        valueTemp =
          parseFloat(arr[0]) === parseFloat(arr[0])
            ? arr[0].toString() + "." + arr[1].substr(0, Math.abs(precision))
            : parseFloat(arr[1]);
      } else {
        valueTemp = arr[0] + ".";
      }
    }
    // debugger
    return valueTemp;
  };

  const _resolvePoint = (num: number | string) => {
    // 处理带小数点的数字
    let res = num;
    if (res === 0 || res === "") {
      return res;
    }
    if (num?.toString().indexOf(".") > -1) {
      const arr = num?.toString().split(".");
      res =
        parseFloat(arr[0]) +
        "." +
        (arr[1] ? arr[1].substring(0, Math.abs(precision)) : "");
      return res;
    }
    return parseFloat(res?.toString());
  };
  let valueTemp = _IntegerNumber();

  if (max && max < valueTemp) {
    valueTemp = max;
    message.warning(`最大值限制输入${valueTemp}`);
  }
  if (min && min > valueTemp) {
    valueTemp = min;
    message.warning(`最小值限制输入${valueTemp}`);
  }
  return valueTemp;
};

// 富文本转文本
export const transferToText = (html: string) => {
  return html
    ?.replace(/<(style|script|iframe)[^>]*?>[\s\S]+?<\/\1\s*>/gi, "")
    .replace(/<[^>]+?>/g, "")
    .replace(/\s+/g, " ")
    .replace(/ /g, " ")
    .replace(/>/g, " ")
    .replace(/&nbsp;/g, " ");
};

export const UNIT_LIST = [
  // 所有事件的单位全集:年是一位小数，日是整数，其他的两位小数 ，百分号的都允许负数
  "%",
  "日",
  "年",
];
export const UNIT_LIST_FLECT = {
  "%": {
    min: -100,
    max: 100,
    step: "0.00",
    count: 2, //限制2小数位数
  },
  日: {
    min: 0,
    max: 1000,
    step: "0",
    count: 0, //限制整数
  },
  年: {
    min: 0,
    max: 1000,
    step: "0.0",
    count: 1, //限制1位小数位数
  },
  "": {
    min: Number.MIN_SAFE_INTEGER,
    max: Number.MAX_SAFE_INTEGER,
    step: "0.00",
    count: 2, //限制2小数位数
  },
};
/**
 *
 * @param content : 文案内容;
 * @returns str 返回匹配的单位
 */
export const IsExitUnit = (content: string, list: string[]) => {
  // 判断文案是否包含单位
  let str = "";
  list.map((v) => {
    if (content.indexOf(v) > -1) {
      str = v;
    }
  });
  return str;
};
/**
 *
 * @param num : 待处理的数字;
 * @param count : 小数位数;
 * @returns str 返回匹配的字符串
 */
export const ToFixNumber = (
  num: number | string,
  count?: number,
  fixed?: boolean
): number | string => {
  if (!fixed) {
    return num || num === 0 ? num : "-";
  }
  if (isNaN(Number(num))) {
    return "";
  }
  return Number(num).toFixed(count || count === 0 ? count : 2);
};

/**
 *
 * @param data : 待处理的对象;
 * @returns 返回匹配的对象
 */
export const getDataFromObject = (data: any = {}) => {
  //  console.log('data',data);
  let res = {};
  for (let i in data) {
    // console.log('1111111111',i,data[i])
    if (data[i]) {
      res = data[i];
      break;
    }
  }
  return res;
};

/**
 *
 * @param type 当前按钮类型
 */
export const isAuthored = (type: string) => {
  const list = localStorage.getItem("author-button") || "[]";
  const pathname = top.window.location.pathname;
  return JSON.parse(list)[pathname]?.indexOf(type) > -1;
};
/*
 * @param record : 平铺的列表数组
 * @param type : 按照type针对的字段进行合并
 * @returns 返回匹配的列表数组
 */
export const getMergeRecordFromTable = (record: any = [], type: string) => {
  if (!record?.length || !type) {
    return [];
  }
  let tempArr = [];
  let Data = [];
  for (let i = 0; i < record.length; i++) {
    if (tempArr.indexOf(record[i][type]) === -1) {
      Data.push({
        [type]: record[i][type],
        list: [record[i]],
      });
      tempArr.push(record[i][type]);
    } else {
      for (let j = 0; j < Data.length; j++) {
        if (Data[j][type] == record[i][type]) {
          Data[j].list.push(record[i]);
          break;
        }
      }
    }
  }
  console.log("Data", Data);

  return record.map((item: any) => {
    for (let i = 0; i < Data.length; i++) {
      if (Data[i][type] === item[type] && !Data[i].hasSetData) {
        Data[i].hasSetData = true;
        return {
          ...item,
          rowSpan: Data[i]?.list.length,
        };
        break;
      }
    }
    return { ...item, rowSpan: 0 };
  });
};

/**
 * 跳转前转换url特殊字符，%和&
 * @param text: string
 */
export const convertUrl = (text: string) => {
  return text
    .replaceAll(/%/g, "%25")
    .replaceAll(/&/g, "%26")
    .replaceAll("+", "%2B")
    .replaceAll("#", "%23");
};

// 自定义日期面板
export const customDatePicker = (
  date_icon: any,
  idName1?: string,
  idName2?: string
) => {
  const img = document.createElement("img");
  const img2 = document.createElement("img");
  // console.log('idName1', idName1, 'idName2', idName2)
  img.src = date_icon;
  img.alt = "日期";
  img.style.height = `${14}px`;
  img.style.width = `${14}px`;
  img.style.marginRight = `${8}px`;
  img2.src = date_icon;
  img2.alt = "日期";
  img2.style.height = `${14}px`;
  img2.style.width = `${14}px`;
  img2.style.marginRight = `${8}px`;

  const dateDom: any = document.getElementById(idName1 || "date12345");
  const dateDom2: any = document.getElementById(idName2 || "date23456");

  dateDom ? (dateDom.size = 10) : null;
  dateDom2 ? (dateDom2.size = 10) : null;

  const parentDom = dateDom ? dateDom?.parentNode : null;
  const parentDom2 = dateDom2 ? dateDom2?.parentNode : null;

  // console.log(parentDom.getElementsByTagName("img"), parentDom2);
  if (parentDom && parentDom.getElementsByTagName("img")?.length > 0) {
    parentDom.removeChild(parentDom.getElementsByTagName("img")[0]);
  }
  if (parentDom2 && parentDom2.getElementsByTagName("img")?.length > 0) {
    parentDom2.removeChild(parentDom2.getElementsByTagName("img")[0]);
  }
  parentDom && parentDom?.insertBefore(img, dateDom);
  idName1 !== idName2 && parentDom2 && parentDom2?.insertBefore(img2, dateDom2);
};

/*
 * @param record : 平铺的列表数组
 * @param type : 按照type针对的字段进行合并
 * @returns 返回匹配的列表数组
 */

export const getMergeFromChildList = (list: Array<any>, type = "list") => {
  let copyList = [];
  let num = 0;
  let col_index;
  let id;
  for (let i = 0; i < list.length; i++) {
    let element = list[i] || {};
    for (let j = 0; j < element[type]?.length; j++) {
      const item = element[type][j] || {};
      const len = element[type]?.length;
      let copy_ele = { ...element };
      delete copy_ele[type];
      num++;
      // console.log('1111',item)
      if (item?.name == "国债") {
        col_index = num - 1;
        if (item["10Y"]) {
          id = item["10Y"]?.id;
        }
      }
      // console.log('222',item.name,col_index,)

      if (j === 0) {
        copyList.push({
          ...copy_ele,
          ...item,
          rowSpan: len,
          item_id: num,
        });
      } else {
        copyList.push({
          ...copy_ele,
          ...item,
          rowSpan: 0,
          item_id: num,
        });
      }
    }
  }
  // console.log('copyList',copyList)
  return {
    list: copyList,
    arr: [
      {
        col_index: 11,
        row_index: col_index,
        col_name: "10Y",
        row_name: "国债",
        id,
      },
    ],
  };
};

// 监听滚动设置滚动条样式
export const listenScroll = (dom: any, className = "scroll-hidden") => {
  if (!dom) return;
  let timer = null;
  dom.onscroll = () => {
    dom?.classList.remove(className);
    clearTimeout(timer);
    timer = setTimeout(() => {
      dom?.classList.add(className);
    }, 1000);
  };
};

/**
 * 保留小数点几位数, 自动补零, 四舍五入
 * @param num: 数值
 * @param digit: 小数点后位数
 * @returns string
 */
export const toFixed = (num: any, digit: number) => {
  if (Object.is(parseFloat(num), NaN)) {
    return;
  }
  num = parseFloat(num);
  return (
    Math.round((num + Number.EPSILON) * Math.pow(10, digit)) /
    Math.pow(10, digit)
  ).toFixed(digit);
};



// 导出图片
export const Export_Img_Tool = async (container, fileName: string) => {
  const base64ImgtoFile = (dataurl, filename = "file") => {
    //将base64格式分割：['data:image/png;base64','XXXX']
    const arr = dataurl.split(",");
    // .*？ 表示匹配任意字符到下一个符合条件的字符 刚好匹配到：
    // image/png
    const mime = arr[0].match(/:(.*?);/)[1]; //image/png
    //[image,png] 获取图片类型后缀
    const suffix = mime.split("/")[1]; //png
    const bstr = atob(arr[1]); //atob() 方法用于解码使用 base-64 编码的字符串
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], `${filename}.${suffix}`, {
      type: mime,
    });
  };

  const canvas = await html2canvas(container);

  const type = "png";
  const imgData = canvas.toDataURL(type);
  const blob = base64ImgtoFile(imgData);
  const blobUrl = window.URL.createObjectURL(blob);

  const a = document.createElement("a");
  a.href = blobUrl;
  a.download = fileName;
  a.click();
};
